var http = require('http');
var events = require('events');
var fs = require('fs');
const path = require('path');
var formidable = require('formidable');

// 包含上传表单的html文件
var upload_html = fs.readFileSync("upload_file.html");
var error_html = fs.readFileSync("./webpage/error.html");
var nofile_html = fs.readFileSync("./webpage/nofile.html");
// 将其替换为保存上传文件的位置
var upload_path = "files";
// 创建 eventEmitter 对象 
var eventEmitter = new events.EventEmitter();

http.createServer(function (request, response) {
    // 先对特殊符号和中文进行解码
    let decode_url = decodeURIComponent(request.url);
    console.log(decode_url);
    if (decode_url.indexOf("/" + upload_path + "/") != -1) {
        fs.readFile("." + decode_url, function (err, data) {
            response.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });
            response.end(data);
        });
    } else if (decode_url.indexOf("/webpage/") != -1) {
        fs.readFile("." + decode_url, function (err, data) {
            response.writeHead(200, { 'content-type': 'text/html;charset=utf-8' });
            if (!data) {
                response.write(nofile_html);
            }
            response.end(data);
        });
    } else if (eventEmitter.listenerCount(request.url) > 0) {
        // 事件分发
        eventEmitter.emit(request.url, request, response);
    }
    else {
        eventEmitter.emit('404', request, response);
    }
}).listen(8888, () => {
    console.log('Server running at ' + get_host_ip_port());
});

function get_host_ip_port() {
    return "http://101.43.241.226:8888";
}

process.on('uncaughtException', err => {
    console.error('有一个未捕获的错误', err);
    //process.exit(1) //强制性的（根据 Node.js 文档）
})

eventEmitter.on('/uploadform', function (request, response) {
    response.writeHead(200);
    response.write(upload_html);
    console.log('正在上传...');
    return response.end();
});
eventEmitter.on('/fileupload', function (request, response) {
    if (request.method.toLowerCase() == 'post') {
        response.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });
        var form = new formidable.IncomingForm();
        form.parse(request, function (err, fields, files) {
            // oldpath：文件保存到的临时文件夹
            var oldpath = files.file.filepath;
            var newpath = "./" + upload_path + "/" + files.file.originalFilename;
            // 将文件复制到新位置
            fs.rename(oldpath, newpath, function (err) {
                try {
                    response.end(get_host_ip_port() + "/" + upload_path + "/" + files.file.originalFilename);
                    if (!files.file.originalFilename) {
                        console.log("上传失败！ \n上传文件为空");
                    } else {
                        console.log('上传成功！\n' + newpath);
                    }
                } catch (err) {
                    console.log(err.message);
                }
            });
        });
    }
});
eventEmitter.on("/" + upload_path, function (request, response) {
    response.writeHead(200, {
        'content-type': 'text/html;charset=utf-8'
    });
    travel("./" + upload_path, function (filename) {
        var link = get_host_ip_port() + "/" + upload_path + "/" + filename;
        response.write("<a href=" + link + ">" + filename + "</a><br>");
    });
    response.end();
});

// route 404 
eventEmitter.on('404', function (request, response) {
    response.writeHead(404, { 'content-type': 'text/html;charset=utf-8' });
    response.write(error_html);
    return response.end();
});

function travel(dir, callback) {
    fs.readdirSync(dir).forEach((file) => {
        var pathname = path.join(dir, file)
        if (fs.statSync(pathname).isDirectory()) {
            travel(pathname, callback)
        } else {
            callback(file)
        }
    })
}
